<?php

/**
 * This is the model class for table "documents".
 *
 * The followings are the available columns in table 'documents':
 * @property integer $id
 * @property string $code
 * @property string $extension
 * @property string $synopsis
 * @property string $createdAt
 * @property string $updatedAt
 * @property text $files
 */
class Document extends ActiveRecord {

	public $images;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Document the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'documents';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		return array(
			array(
				'images',
				'file',
				'on'=>'insert',
				'maxFiles'=>100,
				'types'=>'jpg, jpeg, gif, png, tif',
			),
			array('code, synopsis', 'required'),
			array('code', 'length', 'max'=>255),
			array('code, synopsis', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		return array();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'images'=>'Image files',
			'code'=>'Number',
			'extension'=>'Type',
			'synopsis'=>'Synopsis',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		$criteria = new CDbCriteria;

		$criteria->compare('code', $this->code, true);
		$criteria->compare('synopsis', $this->synopsis, true);

		return new CActiveDataProvider($this, array('criteria'=>$criteria));
	}

	protected function beforeSave() {
		$this->images = CUploadedFile::getInstances($this, 'images');
		$this->extension = 'pdf';
		$files = array();
		foreach ($this->images as $image) {
			$files[] = $image->name;
		}
		$this->files = implode("\n", $files);
		return parent::beforeSave();
	}

	protected function afterSave() {
		parent::afterSave();
		$this->saveImages();
		if ($this->extension == 'pdf') {
			$this->createPdf();
		} else {
			$this->createTiff();
		}
	}

	protected function afterFind() {
		parent::afterFind();
		$this->files = explode("\n", $this->files);
	}

	protected function afterDelete() {
		parent::afterDelete();
		if ($this->extension == 'pdf') {
			$this->deletePdf();
		} else {
			$this->deleteTiff();
		}
		$this->deleteImages();
	}

	protected function saveImages() {
		if (!$this->images) {
			return;
		}

		$folder = Yii::app()->params['files'] . '/documents';
		foreach ($this->images as $image) {
			$path = "{$folder}/originals/{$this->id}.{$image->name}";
			$image->saveAs($path);
			if (strtolower($image->extensionName) == 'tif') {
				$pages = new Imagick($path);
				$names = explode('.', $image->name);
				$name = $names[0];
				foreach ($pages as $i=>$page) {
					$path = "$folder/originals/$this->id.$name.$i.png";
					$page->writeimage($path);
					$page->thumbnailImage(200, 0);
					$path = "$folder/thumbnails/$this->id.$name.$i.jpg";
					$page->writeImage($path);
				}
			} else {
				$thumbnail = new ImageFile($path);
				$names = explode('.', $image->name);
				$path = "{$folder}/thumbnails/{$this->id}.{$names[0]}.jpg";
				$thumbnail->saveAsJpeg($path, 200);
			}
		}
	}

	protected function createPdf() {
		if (!$this->images) {
			return;
		}

		$pdf = new ETcPdf();
		$pdf->SetCreator('Miyabi');
		$pdf->SetAuthor('Miyabi');
		$pdf->SetTitle($this->code);
		$pdf->setPrintHeader(false);
		$pdf->SetMargins(0, 0);
		$breakMargin = $pdf->getBreakMargin();
		$auto_page_break = $pdf->getAutoPageBreak();
		$pdf->SetAutoPageBreak(false, 0);

		$folder = Yii::app()->params['files'] . '/documents';
		foreach ($this->images as $image) {
			$path = "{$folder}/originals/{$this->id}.{$image->name}";
			if (strtolower($image->extensionName) == 'tif') {
				$pages = new Imagick($path);
				$names = explode('.', $image->name);
				$name = $names[0];
				foreach ($pages as $i=>$page) {
					$path = "$folder/originals/$this->id.$name.$i.png";
					$this->addImagePage($pdf, $path);
				}
			} else {
				$this->addImagePage($pdf, $path);
			}
		}

		$pdf->SetAutoPageBreak($auto_page_break, $breakMargin);
		$folder = Yii::app()->params['files'] . '/documents';
		$pdf->Output("$folder/{$this->id}.pdf", 'F');
	}

	protected function addImagePage($pdf, $image) {
		$pdf->AddPage();
		$w = 210; // 210 mm A4
		$h = 297; // 297 mm A4
		$f = false;
		$pdf->Image(
			$image, 0, 0, $w, $h, '', '', '', true, 300, '', $f, $f, 0, 'MC'
		);
		$pdf->setPageMark();
	}

	protected function deletePdf() {
		$folder = Yii::app()->params['files'] . '/documents';
		$filename = "{$folder}/{$this->id}.{$this->extension}";
		if (file_exists($filename)) {
			unlink($filename);
		}
	}

	protected function createTiff() {
		
	}

	protected function deleteTiff() {
		
	}

	public function getThumbnailUrl() {
		$baseUrl = Yii::app()->request->baseUrl;
		$file = $this->files[0];
		$ext = substr($file, -3, 3);
		$names = explode('.', $file, -1);
		if (strtolower($ext == 'tif')) {
			$filename = $this->id . '.' . implode('.', $names) . '.0.jpg';
		} else {
			$filename = $this->id . '.' . implode('.', $names) . '.jpg';
		}
		return "$baseUrl/files/documents/thumbnails/$filename";
	}

	public function getThumbnailUrls() {
		$baseUrl = Yii::app()->request->baseUrl;
		$thumbFolder = Yii::app()->params['files'] . '/documents/thumbnails';
		$urls = array();
		foreach ($this->files as $file) {
			$ext = substr($file, -3, 3);
			$names = explode('.', $file, -1);
			$name = implode('.', $names);
			if (strtolower($ext == 'tif')) {
				$count = 0;
				while (true) {
					$filename = "$this->id.$name.$count.jpg";
					$path = "$thumbFolder/$filename";
					if (file_exists($path)) {
						$u = "$baseUrl/files/documents/thumbnails/$filename";
						$urls[] = $u;
					} else {
						break;
					}
					$count++;
				}
			} else {
				$filename = "$this->id.$name.jpg";
				$urls[] = "$baseUrl/files/documents/thumbnails/$filename";
			}
		}
		return $urls;
	}

}